const express = require('express')
const fs = require('fs')
const Student = require('./student')
const router = express.Router()

// 首页获取数据
router.get('/', (req, res) => {
  Student.find(function (err, students) {
    if (err) {
      return res.statusCode(500).send('Server err.')
    }
    res.render('index.html', {
      students: students
    })
  })
})

// 进入新添加页面
router.get('/students/new', (req, res) => {
  res.render('new.html')
})

// 新添加人
router.post('/students/new', (req, res) => {
  new Student(req.body).save((err, ret) => {
    if (err) {
      return res.statusCode(500).send('Server error')
    }
    res.redirect('/')
  })
})

// 编辑页面
router.get('/students/edit', (req, res) => {
  Student.findOne({
    _id: req.query.id
  }, (err, ret) => {
    if (err) {
      return res.statusCode(500).send('Server error')
    }
    res.render('edit.html', {
      student: ret
    })
  })
})

// 提交更新
router.post('/students/edit', (req, res) => {
  console.log(req.body.id.replace(/\"/g, ''))
  Student.findByIdAndUpdate({
    _id: req.body.id.replace(/\"/g, '')
  }, req.body, (err, ret) => {
    if (err) {
      return res.statusCode(500).send('Server error')
    }
    console.log('更新成功')
    res.redirect('/')
  })
})

// 删除
router.get('/students/delete', (req, res) => {
  console.log(req.query.id)
  Student.findByIdAndDelete(req.query.id, (err, ret) => {
    if (err) {
      return res.statusCode(500).send('Server error')
    }
    console.log('删除成功')
    res.redirect('/')
  })
})

module.exports = router